package com.yanx.common.result;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.NumberUtil;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.yanx.common.page.PageConstant;
import com.yanx.common.page.PageHelper;
import com.yanx.common.page.cursor.CursorPageVo;
import com.yanx.common.page.offset.OffsetPageVo;
import com.yanx.common.utils.String_;
import com.yanx.common.utils.ThreadLocal_;
import lombok.Getter;
import lombok.Setter;

import java.math.BigDecimal;

/**
 * 返回统一的数据格式
 */
@Getter
@Setter
@JsonInclude(JsonInclude.Include.NON_NULL)
public class PageResult<T> extends Result<T> implements IResult<T> {

    private static final long serialVersionUID = 1L;

    /**
     * 分页数据
     */
    private OffsetPageVo paging;

    /**
     * 分页数据
     */
    private CursorPageVo cursor;


    @Override
    public void initPaging() {
        if (String_.equals(PageHelper.getPageType(), PageConstant.Type.CURSOR)) {
            this.setCursor(new CursorPageVo());
        } else {
            this.setPaging(new OffsetPageVo());
        }
        ThreadLocal_.remove();
    }

    public Integer getPageNo() {
        return this.getPaging().getPage();
    }

    public Integer getPageSize() {
        return this.getPaging().getSize();
    }

    public Long getTotalNum() {
        return this.getPaging().getTotal();
    }

    public Integer getTotalPage() {
        if (getTotalNum() == null || getPageSize() == null) {
            return null;
        }
        BigDecimal div = NumberUtil.div(getTotalNum(), getPageSize());
        return Convert.toInt(Math.ceil(div.doubleValue()));
    }

    //兼容
    public T getDatas() {
        return this.getData();
    }

    //兼容ruoyi
    public Long getTotal() {
        return this.getTotalNum();
    }

    public T getRows() {
        return this.getData();
    }

}
